package com.omg.api.handle;

import java.util.List;

import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.omg.api.argument.Argument;
import com.omg.api.argument.NotificationArgument;
import com.omg.api.result.Result;
import com.omg.api.result.body.NotificationBody;
import com.omg.api.result.header.NotificationHeader;
import com.omg.constant.ResponseCode;
import com.omg.persistence.dao.lifepoint.entity.LPActivityRequest;
import com.omg.persistence.dao.lifepoint.entity.LPFriendRequest;
import com.omg.persistence.delegate.lifepoint.LPActivityRequestDelegate;
import com.omg.persistence.delegate.lifepoint.LPFriendRequestDelegate;

/**
 * 
 * @author xiazhiquan
 * 
 *         May 29, 2011
 */
public class NotificationHandler extends Handler {

	private static final Logger LOG = Logger
			.getLogger(NotificationHandler.class.getName());

	private static NotificationHandler instance = null;

	static {
		instance = new NotificationHandler();
	}

	public static NotificationHandler getInstance() {
		return instance;
	}

	public String handle(Argument argument) throws Exception {

		String userid = ((NotificationArgument) argument).getUserid();

		List<LPFriendRequest> lpFriendRequests = LPFriendRequestDelegate
				.getInstance().getFriendRequestsByUseridAndIsnew(userid, true);

		List<LPActivityRequest> lpActivityRequests = LPActivityRequestDelegate
				.getInstance()
				.getActivityRequestsByUseridAndIsnew(userid, true);

		return getJson(lpFriendRequests, lpActivityRequests);
	}

	private final String getJson(List<LPFriendRequest> lpFriendRequests,
			List<LPActivityRequest> lpActivityRequests) throws Exception {
		try {

			// construct result
			Result result = new Result();

			// header
			NotificationHeader header = new NotificationHeader();
			header.setRespcode(ResponseCode.AP_E_Succ);
			result.setHeader(header);

			// body
			NotificationBody body = new NotificationBody();
			body.setActivity_requests(lpActivityRequests);
			body.setFriend_requests(lpFriendRequests);
			result.setBody(body);

			return new Gson().toJson(result);
		} catch (Exception e) {
			e.printStackTrace();
			String errorMsg = e.getMessage();
			LOG.error(errorMsg, e);
			throw new Exception(""
					+ (errorMsg != null && !errorMsg.isEmpty() ? errorMsg
							: ResponseCode.AP_E_Info_UnkownError));
		}
	}

}
